import { getAction } from '@/api/manage'
import { USER_AUTH, SYS_BUTTON_AUTH } from '@/store/mutation-types'

export const ActionsMixin = {
  data() {
    return {
      permissionList: []
    }
  },
  created() {
    this.loadPermissions()
  },
  methods: {
    loadPermissions() {
      // 从sessionStorage获取权限
      let authList = JSON.parse(sessionStorage.getItem(USER_AUTH) || '[]')

      // 如果sessionStorage中没有权限，尝试从localStorage获取
      if (!authList || authList.length === 0) {
        authList = JSON.parse(localStorage.getItem(USER_AUTH) || '[]')
      }

      // 从按钮权限中获取
      const buttonAuth = JSON.parse(
        sessionStorage.getItem(SYS_BUTTON_AUTH) || localStorage.getItem(SYS_BUTTON_AUTH) || '[]'
      )

      // 合并权限
      if (buttonAuth && buttonAuth.length > 0) {
        authList = authList.concat(buttonAuth)
      }

      // 提取action字段
      this.permissionList = authList.map((auth) => auth.action || auth)
    },
    /**
     * 检查是否有权限
     * @param {string} permission - 权限编码
     * @returns {boolean} - 是否有权限
     */
    hasPermission(permission) {
      if (!permission) {
        return true // 如果未指定权限，默认有权限
      }

      // 检查权限列表中是否包含指定权限
      if (this.permissionList.includes(permission)) {
        return true
      }

      // 检查权限列表中是否包含以逗号分隔的多个权限
      for (let perm of this.permissionList) {
        if (perm && perm.includes(',')) {
          const perms = perm.split(',')
          if (perms.includes(permission)) {
            return true
          }
        }
      }

      return false
    }
  }
}